<template>
  <el-select
    v-model="selectValue"
    v-bind="$attrs"
    :multiple="multiple"
    :filterable="filterable"
    :allow-create="allowCreate"
    :clearable="clearable"
    :loading="loading"
    :placeholder="placeholder"
    @change="handleChange"
    @focus="handleFocus"
    @blur="handleBlur"
    @visible-change="handleVisibleChange"
  >
    <el-option
      v-for="option in normalizedOptions"
      :key="option.value"
      :label="option.label"
      :value="option.value"
      :disabled="option.disabled"
    />
  </el-select>
</template>

<script setup>
import { computed, ref } from 'vue'
import { ElSelect, ElOption } from 'element-plus'

const props = defineProps({
  modelValue: [String, Number, Array],
  options: {
    type: Array,
    default: () => []
  },
  multiple: Boolean,
  filterable: Boolean,
  allowCreate: Boolean,
  clearable: {
    type: Boolean,
    default: true
  },
  loading: Boolean,
  placeholder: String
})

const emit = defineEmits(['update:modelValue', 'change', 'focus', 'blur', 'visible-change'])

const selectValue = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

// 标准化选项格式
const normalizedOptions = computed(() => {
  return props.options.map(option => {
    if (typeof option === 'string' || typeof option === 'number') {
      return {
        label: String(option),
        value: option,
        disabled: false
      }
    }
    return {
      label: option.label || String(option.value),
      value: option.value,
      disabled: option.disabled || false
    }
  })
})

const handleChange = (value) => {
  emit('change', value)
}

const handleFocus = (event) => {
  emit('focus', event)
}

const handleBlur = (event) => {
  emit('blur', event)
}

const handleVisibleChange = (visible) => {
  emit('visible-change', visible)
}
</script>